<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Models\GoodsCart;
use Illuminate\Http\Request;


class GoodsCartController extends Controller
{
    // 购物车列表
    public function index()
    {
        $list = GoodsCart::from('goods_cart as cart')
            ->leftJoin('goods', 'goods.id', '=', 'cart.goods_id')
            ->where('cart.user_id', auth('wechat')->id())
            ->orderByDesc('cart.id')
            ->get(['goods.*']);
        return $this->writeJson(0, $list);
    }

    // 加入购物车
    public function add(Request $request)
    {
        $goods_id = $request->post('goods_id');
        if (empty($goods_id)) {
            return $this->writeJson(500, null, '请选择商品');
        }

        $user_id = auth('wechat')->id();
        $model = GoodsCart::whereUserId($user_id)
            ->where('goods_id', $goods_id)
            ->first();
        if (empty($model)) {
            $model = new GoodsCart();
            $model->user_id = $user_id;
            $model->goods_id = $goods_id;
            $model->num = 1;
            $model->save();
        } else {
            $model->increment('num');
        }
        return $this->writeJson(0, null, '加入购物车成功');
    }

    // 编辑购物车数量
    public function editNum(Request $request)
    {
        $num = $request->post('num');
        $goods_id = $request->post('goods_id');
        if (empty($goods_id)) {
            return $this->writeJson(500, null, '请选择商品');
        }
        if ($num < 1) {
            return $this->writeJson(500, null, '数量不能小于1');
        }
        $model = GoodsCart::whereUserId(auth('wechat')->id())
            ->where('goods_id', $goods_id)
            ->first();
        if (empty($model)) {
            return $this->writeJson(500, null, '修改购物车商品不存在');
        }
        $model->num = $num;
        $model->save();
        return $this->writeJson(0, null, '修改成功');
    }

    // 删除购物车商品
    public function del(Request $request)
    {
        $goods_id = $request->post('goods_id');
        if (empty($goods_id)) {
            return $this->writeJson(500, null, '请选择商品');
        }
        $model = GoodsCart::whereUserId(auth('wechat')->id())
            ->where('goods_id', $goods_id)
            ->first();
        if (empty($model)) {
            return $this->writeJson(500, null, '购物车商品不存在');
        }
        $model->delete();
        return $this->writeJson(0, null, '删除成功');
    }
}
